/** @odoo-module **/
import init_grid_options from './ag_grid/gridOptions.js'
import {onFullscreenChange,formatId,toObj,getMonths,keepTwoDecimal,getDaysArr} from "./ag_grid/tool.js";
import {Toast} from './components/Toast.js';
import {SalesModal} from './components/SalesModal.js';
import {CostModal} from './components/CostModal.js';
import CustomHeader from "./ag_grid/CustomHeader.js";


class GroupRowInnerRenderer {
    // 初始化
    init(params){

        const eGui = document.createElement('div');
        let _html = '';
        let value = params.value;
        let owl = params.context.owl_widget;
        this.owl = owl;

        let Count = params.node.allChildrenCount;

        eGui.className = 'd-flex align-items-center gap-1';
        _html += `<div class="" style="min-width:70px">${value}（${Count}）</div>`;
        // _html += `<button type="button" class="btn btn-outline-primary btn-xs" data-value="${value}" style="padding: 0 4px">打印</button>`;
        eGui.innerHTML = _html;
        this.eGui = eGui;

        // let _this = this;
        // eGui.getElementsByClassName('btn')[0].onclick = _.debounce(_this.print.bind(_this),300);

    }
    print(e){
        return this.owl.print(e)
    }
    // 插入页面
    getGui() {
        return this.eGui;
    }
    // 刷新
    refresh(params) {
        return false;
    }

    destroy() {

    }
}

class saleCellRenderer {
    init(params) {
        // console.log(params);
        let _this = this;
        this.owl = params.context.owl_widget;
        let el = document.createElement('div');
        el.className = 'd-flex align-items-center';
        el.style = 'justify-content: space-between;';
        let value = params.value;
        let fillColor = '#71639e';
        let _html = '';
        _html+= `<div>${params.valueFormatted}</div>`;
        if(Number(params.valueFormatted)!=0){
            _html+=`<svg style="vertical-align: middle;fill: currentColor;overflow: hidden;cursor: pointer" t="1689162163405" class="iconBtn" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1554" width="18" height="18" data-spm-anchor-id="a313x.7781069.0.i3"><path d="M819.2 0H204.8a136.533333 136.533333 0 0 0-136.533333 136.533333v750.933334a136.533333 136.533333 0 0 0 136.533333 136.533333h614.4a136.533333 136.533333 0 0 0 136.533333-136.533333V136.533333a136.533333 136.533333 0 0 0-136.533333-136.533333z m68.266667 887.466667a68.266667 68.266667 0 0 1-68.266667 68.266666H204.8a68.266667 68.266667 0 0 1-68.266667-68.266666V136.533333a68.266667 68.266667 0 0 1 68.266667-68.266666h614.4a68.266667 68.266667 0 0 1 68.266667 68.266666z" fill="" p-id="1555"></path><path d="M735.914667 273.066667h-307.2a34.133333 34.133333 0 0 0 0 68.266666h307.2a34.133333 34.133333 0 0 0 0-68.266666zM735.914667 477.866667h-307.2a34.133333 34.133333 0 0 0 0 68.266666h307.2a34.133333 34.133333 0 0 0 0-68.266666zM735.914667 682.666667h-307.2a34.133333 34.133333 0 0 0 0 68.266666h307.2a34.133333 34.133333 0 0 0 0-68.266666zM313.344 273.066667h-25.258667a34.133333 34.133333 0 0 0 0 68.266666h25.941334a34.133333 34.133333 0 0 0 0-68.266666zM313.344 477.866667h-25.258667a34.133333 34.133333 0 0 0 0 68.266666h25.941334a34.133333 34.133333 0 0 0 0-68.266666zM313.344 682.666667h-25.258667a34.133333 34.133333 0 0 0 0 68.266666h25.941334a34.133333 34.133333 0 0 0 0-68.266666z" fill="${fillColor}" p-id="1556"></path></svg>`
        }
        el.innerHTML = _html;
        el.querySelectorAll('.iconBtn').forEach(function (e){
            e.addEventListener('click',function (ev){
                ev.stopPropagation();
                if(params.column.colId == 'totalSalesAmount'){
                    _this.owl.openSalesModal(params);
                }
                if(params.column.colId == 'totalCostAmount'){
                    _this.owl.openCostModal(params);
                }
            })
        });
        this.eGui = el;

    }
    getGui() {
        return this.eGui;
    }

    refresh(params) {
        return false;
    }
}

const {
    markup,
    Component,
    onWillStart,
    useEnv,
    useSubEnv,
    useChildSubEnv,
    useRef,
    useState,
    mount,
    xml,
    whenReady,
    onMounted,
    onError,
    loadFile,
    onWillUpdateProps,
    useEffect,
    useComponent,
    EventBus
} = owl;

class Root extends Component {

    setup() {

        this.myGrid_ref = useRef('myGrid');
        this.recordData = [];//表格的基础数据
        this.addRowMaxId = '';//表格最大的id
        this.rowData = [];//表格数据

        this.index = {
            cus_loc:[]
        };
        this.settlement_data = {};
        this.dinner_mode_cus = {};
        this.dinner_mode_category = {};
        this.org_group_category = {};
        this.cus_sales_category = {};
        this.dinner_type_category = {};
        this.cus_loc_name = {};
        this.cus_loc = {};

        this.monthList = getMonths(14);
        this.dinnerTypeList = [
            {name: '早餐', id: 'dn1'},
            {name: '中餐', id: 'dn2'},
            {name: '晚餐', id: 'dn3'},
            {name: '夜餐', id: 'dn5'},
        ];
        this.dinnerType = toObj(this.dinnerTypeList,'id');
        this.salesCategoryList = [];
        this.salesCategory = {};
        this.salesCategoryName = {};
        this.tableHead = {};

        this.monthList = getMonths(14);
        let year_month = this.monthList.find(e => e === this.props.year_month);

        if (!year_month) {
            year_month = this.props.year_month;
            this.monthList.push(year_month);
            console.log('该月份不存在, 需要加入到月份列表中!!!');
        }
        this.year_month = year_month;

        this.sidebarFilterReg = {};//所有的正则
        this.checkedSidebarFilterReg = {};//已选择的
        this.dinner_mode_cus = {};

        console.log(this.props);

        this.bus = new EventBus();

        useSubEnv({
            bus: this.bus
        });

        useChildSubEnv({// 只会在组件的子组件中挂载公共数据及方法
            closeToast: () => {
                this.state.toastOpen = false;
                this.state.toastData = {};
            },
            openToast:(data)=>{
                this.state.toastOpen = true;
                this.state.toastData = {...data};
            },
            getIndex: () => {
                return this.index;
            },
            getGlobal:()=>{
                return this.global
            },
            closeSalesModal:()=>{
                this.state.SalesModalOpen = false;
                this.state.SalesModalData = {};
            },
            openSalesModal:()=>{
                this.openSalesModal();
            },
            closeCostModal:()=>{
                this.state.CostModalOpen = false;
                this.state.CostModalData = {};
            }
        });

        let days = getDaysArr(year_month,1);
        let endDate = days[days.length-1].split('-')[2];

        this.index = {};
        this.global = {};
        this.state = useState({
            loading:false,
            isMenuMode: true,
            toastOpen: false,
            toastData: {},//提示消息
            SalesModalOpen:false,
            SalesModalData:{},
            CostModalOpen:false,
            CostModalData:{},
            tableConfig:{
                showZero:true
            },
            startDate:'01',
            endDate:endDate,
            month:year_month

        });

        onWillStart(async () => await this.LoadData());
        onWillUpdateProps(async next_props => await this.LoadData());
        onMounted(this.RenderAG);

        this.handleExpandAll = _.debounce(this.expandAll,300);
        this.handleCollapseAll = _.debounce(this.collapseAll,300);
        this.handleDateFilterChange = _.debounce(this.dateFilterChange,300);
    }
    async LoadTestSaleData(year_month_day){
        let data = {'sales_record': [{'date': '2024-06-02', 'dinner_type_id': 52, 'cus_loc_id': 284, 'sales_category_id': 14, 'sales_amount': 7992.0}], 'dinner_type_category': [{'id': 51, 'name': '早餐'}, {'id': 52, 'name': '中餐'}, {'id': 53, 'name': '晚餐'}, {'id': 89, 'name': '夜餐'}], 'sales_category': [{'id': 14, 'name': '快餐'}, {'id': 15, 'name': '特色'}],'cus_loc':[{'cus_loc_id':284,'name':'测试'}]};

        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve(data);
            }, 1000);
        });
    }
    async LoadTestCostData(){
        let data = await fetch('./json/成本明细.json')
            .then((response) => response.json());
        return data;
    }
    async openCostModal(rowItem){
        let year_month_day = 0;
        let cost_center_id = 0;
        let cus_group_id = 0;
        if(rowItem){
            if(rowItem.data){
                year_month_day = rowItem.data.date;
                cost_center_id = rowItem.data.cost_center_id;
                cus_group_id = rowItem.data.cus_group_id;
            }
            if(rowItem.node.field == 'date'){
                year_month_day = rowItem.node.key;
                cost_center_id = 0;
                cus_group_id = 0;
            }
            if(rowItem.node.field == 'cost_center_name'){
                year_month_day = rowItem.node.allLeafChildren[0].data.date;
                cost_center_id = rowItem.node.allLeafChildren[0].data.cost_center_id;
                cus_group_id = 0;
            }
        }

        let year_month = this.props.year_month;
        console.log(this.props.year_month);
        console.log(year_month_day);
        console.log(cost_center_id);
        console.log(cus_group_id);
        let load_func = this.props.CanteenLoadCostData ? this.props.CanteenLoadCostData : this.LoadTestCostData.bind(this);
        let data = await load_func(year_month, year_month_day,cost_center_id,cus_group_id);
        console.log(data);
        let {
            rel_partner,
            cost_item_record,
            cost_object
        } = data;
        this.state.CostModalOpen = true;
        this.state.CostModalData = {
            rel_partner,
            cost_item_record,
            cost_object
        };
    }
    async openSalesModal(rowItem){
        // console.log(rowItem);
        let year_month_day = 0;
        let cost_center_id = 0;
        let cus_group_id = 0;
        if(rowItem){
            if(rowItem.data){
                year_month_day = rowItem.data.date;
                cost_center_id = rowItem.data.cost_center_id;
                cus_group_id = rowItem.data.cus_group_id;
            }
            if(rowItem.node.field == 'date'){
                year_month_day = rowItem.node.key;
                cost_center_id = 0;
                cus_group_id = 0;
            }
            if(rowItem.node.field == 'cost_center_name'){
                year_month_day = rowItem.node.allLeafChildren[0].data.date;
                cost_center_id = rowItem.node.allLeafChildren[0].data.cost_center_id;
                cus_group_id = 0;
            }
        }

        let year_month = this.state.month;
        console.log(this.props.year_month);
        console.log(year_month_day);
        console.log(cost_center_id);
        console.log(cus_group_id);
        let load_func = this.props.CanteenLoadSaleData ? this.props.CanteenLoadSaleData : this.LoadTestSaleData.bind(this);
        let data = await load_func(year_month, year_month_day,cost_center_id,cus_group_id);
        let {
            sales_record,
            dinner_type_category,
            sales_category,
            cus_loc
        } = data;
        this.state.SalesModalOpen = true;
        this.state.SalesModalData = {
            sales_record,
            dinner_type_category,
            sales_category,
            cus_loc
        };
    }
    expandAll(){
        this.gridOptions.api.expandAll();
    }
    collapseAll(){
        this.gridOptions.api.collapseAll();
    }

    // 全部打印
    printAll(e){
        let year_month = this.year_month;
    }
    //打印
    print(e){

    }
    // 更换月份
    selectMonth(e) {
        console.log('选择月份', this.state.month);
        let year_month = this.state.month;
        this.state.startDate = '01';
        let days = getDaysArr(year_month,1);
        let endDate = days[days.length-1].split('-')[2];
        this.state.endDate = endDate;
        this.LoadData(year_month);
    }
    // 测试用的异步
    request(data) {
        return new Promise((resolve, reject) => {
            setTimeout(() => {
                resolve({
                    ...data
                });
            }, 500);
        });
    }

    onFullscreenChange(e){
        console.log(e);
        let isMenuMode = false;
        if (document.fullscreenElement) {
            console.log('进入全屏')
        } else {
            console.log('退出全屏')
            isMenuMode = true;
        }
        this.state.isMenuMode = isMenuMode;
        this.bus.trigger('setIsMenuMode', isMenuMode);
        if (this.props.toggleMenuMode) {
            this.props.toggleMenuMode(this.state.isMenuMode);
        }
    }
    async LoadTestData() {

        let canteen_cost_report = await fetch('./json/canteen_cost_report.json')
            .then((response) => response.json());
        let cus_group = await fetch('./json/cus_group.json')
            .then((response) => response.json());
        let cost_category = await fetch('./json/cost_category.json')
            .then((response) => response.json());
        let cost_center = await fetch('./json/cost_center.json')
            .then((response) => response.json());
        let cost_type_dic = await fetch('./json/cost_type_dic.json')
            .then((response) => response.json());
        // let data = await fetch('./json/data.json')
        //     .then((response) => response.json());

        return {
            canteen_cost_report,
            cus_group,
            cost_category,
            cost_center,
            cost_type_dic
        }

        // return data

    }

    async LoadData(year_month) {
        this.state.loading = true;
        console.log(`加载数据 `); // 开辟加载父类数据结构逻辑!!!
        let load_func = this.props.LoadData ? this.props.LoadData : this.LoadTestData.bind(this);

        let data = await load_func(year_month);
        // console.log(data);

        let {
            canteen_cost_report,
            cus_group,
            cost_category,
            cost_center,
            cost_type_dic
        } = data;
        this.index = {
            canteen_cost_report,
            cus_group,
            cost_category,
            cost_center,
            cost_type_dic
        };
        this.global = {
            cus_group:toObj(cus_group,'id'),
            cost_category:toObj(cost_category,'id'),
            cost_center:toObj(cost_center,'id'),
            cost_type_dic:cost_type_dic,
            cost_category_by_name:toObj(cost_category,'name'),
        };

        this.setRecordData();
        this.setTableHead();
        if(!year_month){
            this.setSidebarFilter();
            this.setCostCenterFilter();
            this.setCusGroupFilter();
        }
        this.state.loading = false;
    }

    //设置表格基础数据
    setRecordData(){
        // console.log(days);
        let {canteen_cost_report } = this.index;
        let recordObj = {};
        let recordData = [];
        canteen_cost_report.forEach(v=>{
            let {cost_amount,cost_category_name,cost_center_id,cost_ratio,date,sales_amount,id,cus_group_id} = v; // cost_category_id
            if(!cus_group_id) cus_group_id = 0;
            let cost_category_id = this.global.cost_category_by_name[cost_category_name].id;
            let key = `${date}||${cost_center_id}||${cus_group_id}`;
            !recordObj[key] && (recordObj[key]  = {
                totalCostAmount:0,
                totalCostRatio:0,
                totalSalesAmount:0,
            });
            recordObj[key][`cost||${cost_category_id}||cost_amount`] = cost_amount;
            recordObj[key][`cost||${cost_category_id}||cost_ratio`] = cost_ratio;
            recordObj[key][`cost||${cost_category_id}||sales_amount`] = sales_amount;
            recordObj[key].totalCostAmount += cost_amount;
            // recordObj[key].totalSalesAmount += sales_amount;
            recordObj[key].totalSalesAmount = sales_amount;
            recordObj[key].totalMarginAmount = sales_amount - recordObj[key].totalCostAmount;
        });
        // console.log(canteen_cost_report.filter(v=>v.cost_center_id == 332 && v.cus_group_id == 110 && v.date == '2024-01-19'));
        this.addRowMaxId = 0;
        for(let key in recordObj){
            let [date,cost_center_id,cus_group_id] = key.split('||');
            this.addRowMaxId++;
            let cost_center_name = this.global.cost_center[cost_center_id].name;
            let cus_group_name = '无';
            if(cus_group_id){
                try {
                    // console.log(cus_group_id);
                    cus_group_name = this.global.cus_group[cus_group_id].name;
                }catch (e) {

                }

            }
            recordData.push({
                ...recordObj[key],
                id:this.addRowMaxId,
                date:date,
                cost_center_id:Number(cost_center_id),
                cost_center_name:cost_center_name,
                cus_group_id:Number(cus_group_id),
                cus_group_name:cus_group_name

            });
        }
        this.recordData = recordData;
        this.rowData = recordData;
        // console.log(recordData);

        if(this.gridOptions){
            this.gridOptions.api.setRowData(this.rowData);
            this.gridOptions.api.setColumnDefs(this.setColumnDefs());
            this.gridOptions.api.refreshHeader();
            this.gridOptions.api.redrawRows();
            // this.costCenterFilterChange();
        }
    }

    setConfig(){

    }
    setShowZero(){
        this.gridOptions.api.redrawRows();
    }
    setCostCenterFilter(){
        let costCenterFilter = {};
        this.costCenterFilterForm.forEach(v=>{
            costCenterFilter[v.id] = true;
        });
        this.state.costCenterFilter = costCenterFilter;
        this.state.costCenterFilterCheckAll = true;
    }
    setCusGroupFilter(){
        let cusGroupFilter = {};
        this.cusGroupFilterForm.forEach(v=>{
            cusGroupFilter[v.id] = true;
        });
        this.state.cusGroupFilter = cusGroupFilter;
        this.state.cusGroupFilterCheckAll = true;
    }
    setSidebarFilter() {
        let { user_config } = this.index;
        let sidebarFilter = {};
        let sidebarFilterReg = {};
        // 设置
        this.sidebarFilterForm.forEach(v => {
            !sidebarFilter[v.key] && (sidebarFilter[v.key] = {});
            !sidebarFilterReg[v.key] && (sidebarFilterReg[v.key] = {});
            v.children.forEach(item => {
                let flag = true;
                // if(item.user_config_key){
                //     flag = eval('user_config.'+item.user_config_key);
                // }
                // if(item.id == 'forecast_price' || item.id == 'result_price'){
                //     flag = false;
                // }
                sidebarFilter[v.key][item.id] = flag;
                sidebarFilterReg[v.key][item.id] = item.reg||'';
            })
        });
        this.state.sidebarFilter = sidebarFilter;
        this.sidebarFilterReg = sidebarFilterReg;
        this.updataCheckedSidebarFilterReg();
        this.isCheckAll();
    }
    updataCheckedSidebarFilterReg(){
        let _this = this;
        let showReg = {};
        for(let key1 in _this.state.sidebarFilter){
            showReg[key1] = []
            for(let key2 in _this.state.sidebarFilter[key1]){
                if(_this.state.sidebarFilter[key1][key2]){
                    let reg = _this.sidebarFilterReg[key1][key2];
                    showReg[key1].push(reg);
                }
            }
        }
        this.checkedSidebarFilterReg = showReg;
    }
    // 左侧筛选-检查是否全选
    isCheckAll() {
        let sidebarFilterCheckAll = {};
        for (let key in this.state.sidebarFilter) {
            sidebarFilterCheckAll[key] = true;
            for (let name in this.state.sidebarFilter[key]) {
                if (!this.state.sidebarFilter[key][name]) {
                    sidebarFilterCheckAll[key] = false;
                }
            }
        }
        this.state.sidebarFilterCheckAll = sidebarFilterCheckAll;
    }
    get costCenterFilterForm(){
        let _arr = JSON.parse(JSON.stringify(this.index.cost_center));
        return _arr;
    }
    get cusGroupFilterForm(){
        let _arr = JSON.parse(JSON.stringify(this.index.cus_group));
        _arr.push({
            id:'null',name:'无'
        });
        return _arr;
    }

    // 左侧筛选-表单配置
    get sidebarFilterForm() {
        let _arr = [
            {
                name: '显示设置',
                key: 'visable',
                colKey: '',
                children: [
                    {name: '成本金额', id: 'cost_amount',reg:/^cost+\\|\\|[A-Za-z0-9]+\\|\\|cost_amount$/,user_config_key:''},//cost||349||cost_amount
                    {name: '成本比例', id: 'cost_ratio',reg:/^cost+\\|\\|[A-Za-z0-9]+\\|\\|cost_ratio$/,user_config_key:''},//cost||349||cost_ratio
                    {name: '汇总-销售额', id: 'totalSalesAmount',reg:/^totalSalesAmount/,user_config_key:''},
                    {name: '汇总-成本', id: 'totalCostAmount',reg:/^totalCostAmount/,user_config_key:''},
                    {name: '汇总-成本比例', id: 'totalCostRatio',reg:/^totalCostRatio/,user_config_key:''},
                    {name: '汇总-利润', id: 'totalMarginAmount',reg:/^totalMarginAmount/,user_config_key:''},
                    {name: '汇总-利润率', id: 'totalMarginRatio',reg:/^totalMarginRatio/,user_config_key:''},
                ]
            },
            {
                name: '成本类别',
                key: 'costType',
                colKey: '',
                children: []
            },
        ];
        let { cost_type_dic } = this.global;
        for(let cost_type in this.tableHead){
            _arr[1].children.push({
                name:cost_type_dic[cost_type],
                id:cost_type,
                reg:eval('/^'+cost_type+'$/'),
            })
        }
        return _arr;
    }
    costCenterFilterChange(e){
        this.setFilterModel();
        e && this.isCostCenterFilterCheckAll();
    }
    cusGroupFilterChange(e){
        this.setFilterModel();
        e && this.isCusGroupFilterCheckAll();
    }
    dateFilterChange(e){
        this.setFilterModel();
    }
    isCostCenterFilterCheckAll() {
        let costCenterFilterCheckAll = true;
        let obj = this.state.costCenterFilter;
        for (let name in obj) {
            if(!this.state.costCenterFilter[name]){
                costCenterFilterCheckAll = false
            }
        }
        this.state.costCenterFilterCheckAll = costCenterFilterCheckAll;
    }
    isCusGroupFilterCheckAll() {
        let cusGroupFilterCheckAll = true;
        let obj = this.state.cusGroupFilter;
        for (let name in obj) {
             if(!this.state.cusGroupFilter[name]){
                 cusGroupFilterCheckAll = false
             }
        }
        this.state.cusGroupFilterCheckAll = cusGroupFilterCheckAll;
    }
    costCenterFilterChangeAll(e){
        let obj = this.state.costCenterFilter;
        for (let name in obj) {
            this.state.costCenterFilter[name] = this.state.costCenterFilterCheckAll;
        }
        this.costCenterFilterChange();
    }
    cusGroupFilterChangeAll(e){
        let obj = this.state.cusGroupFilter;
        for (let name in obj) {
            this.state.cusGroupFilter[name] = this.state.cusGroupFilterCheckAll;
        }
        this.cusGroupFilterChange();
    }
    startDateOnChange() {
        let endDate = this.state.endDate;
        let item = this.end_date_list.find(v => v == endDate);
        if (!item) {
            this.state.endDate = this.end_date_list[0];
        }
    }

    get start_date_list() {
        let days = getDaysArr(this.state.month,1);
        let arr = days.map(v=>v.split('-')[2]);
        return arr;
    }
    get end_date_list() {
        let days = getDaysArr(this.state.month,1);
        let start_date_list = days.map(v=>v.split('-')[2]);
        let arr = start_date_list.filter(v=> !(Number(v)<Number(this.state.startDate)));
        return arr;
    }
    setFilterModel(){
        let _this = this;
        let cost_center_name_arr = [];
        let cus_group_name_arr = [];
        let date_arr = [];
        for(let id in _this.state.costCenterFilter){
            if(_this.state.costCenterFilter[id]){
                let name = this.global.cost_center[id].name;
                cost_center_name_arr.push(name);
            }
        }
        for(let id in _this.state.cusGroupFilter){
            if(_this.state.cusGroupFilter[id]){
                if(id == 'null'){
                    cus_group_name_arr.push('无');
                }else{
                    let name = this.global.cus_group[id].name;
                    cus_group_name_arr.push(name);
                }
            }
        }
        let startDate = Number(this.state.startDate);
        let endDate = Number(this.state.endDate);
        let days = getDaysArr(this.state.month,1);
        days.forEach(v=>{
            let _date = Number(v.split('-')[2]);
            if(_date >= startDate && _date<=endDate){
                date_arr.push(v);
            }
        });
        // console.log(date_arr);
        let filterModel = {
            date:{
                type: 'contains',
                values: date_arr
            },
            cost_center_name:{
                type: 'contains',
                values: cost_center_name_arr
            },
            cus_group_name:{
                type: 'contains',
                values: cus_group_name_arr
            },
        };
        this.gridOptions.api.setFilterModel(filterModel);
        this.gridOptions.api.onFilterChanged();
    }
    //左侧筛选更改-全选
    sidebarFilterChangeAll(e) {
        let key = e.target.name;
        let obj = this.state.sidebarFilter[key];
        for (let name in obj) {
            this.state.sidebarFilter[key][name] = this.state.sidebarFilterCheckAll[key];
        }
        this.sidebarFilterChange();
    }
    // 左侧筛选更改
    sidebarFilterChange(e) {
        // console.log('------sidebarFilterChange-------');
        // this.updataTableHeadCus();
        e && this.isCheckAll();
        this.updataCheckedSidebarFilterReg();
        // this.updateUserConfig();
        let colIds = this.gridOptions.columnApi.getColumns().map(v=>{return v.colId});
        let showColIds = [];
        let hideColIds = [];
        colIds.forEach(colId=>{
            if(this.isShowColId(colId)){
                showColIds.push(colId);
            }else{
                hideColIds.push(colId);
            }
        });
        // console.log(showColIds);
        this.gridOptions.columnApi.setColumnsVisible(hideColIds, false);
        this.gridOptions.columnApi.setColumnsVisible(showColIds, true);
        this.gridOptions.api.redrawRows();
    }
    setTableHead(){
        let { canteen_cost_report } = this.index;
        let { cost_type_dic, cost_category,cost_category_by_name} = this.global;
        let tableHead = {};
        canteen_cost_report.forEach(v=>{
            let {cost_amount,cost_center_id,cost_category_name,cost_ratio,date,sales_amount,id,cus_group_id} = v; //cost_category_id
            let cost_category_id = cost_category_by_name[cost_category_name].id;
            let cost_type = cost_category[cost_category_id].cost_type;
            !tableHead[cost_type] && (tableHead[cost_type] = {});
            !tableHead[cost_type][cost_category_id] && (tableHead[cost_type][cost_category_id] = true);
        });
        this.tableHead = tableHead;
        console.log(tableHead);
    }
    // 判断该colId是否显示
    isShowColId(colId){
        let showReg = this.checkedSidebarFilterReg;
        let flag = false;
        let alwaysShowColIds = ['cost_center_name_group','cus_group_name','date_group'];//始终显示
        let alwaysHideColIds = ['date','cost_center_name'];//始终隐藏
        if(alwaysShowColIds.includes(colId)){
            flag = true;
            return flag;
        }
        if(alwaysHideColIds.includes(colId)){
            flag = false;
            return flag;
        }
        // console.log(showReg);
        showReg.visable.forEach(reg=>{
            if(reg.exec(colId+'')){
                flag = true;
            }
        });
        if(colId.startsWith('cost||') && flag){
            let flag2 = false;
            let [cost,cost_category_id,type] = colId.split('||');
            // cost||1053||cost_amount
            // cost||1053||cost_ratio
            showReg.costType.forEach(reg=>{
                let _costType = this.global.cost_category[cost_category_id].cost_type;
                if(reg.exec(_costType)){
                    flag2 = true;
                }
            });
            !flag2 && (flag = false);
        }
        // console.log(flag);
        return flag;
    }
    setColumnDefs(){
        // let _this = this;
        let col = [
            {
                headerName: "",
                field: "date",
                hide: true,
                rowGroup: true,
                comparator: (a,b) => {
                    let a_time = 0;
                    let b_time = 0;
                    try {
                        a_time = new Date(a).getTime();
                        b_time = new Date(b).getTime();
                    }catch (e) {

                    }
                    return a_time - b_time;
                },
            },
            {
                headerName: "日期",
                field: "date_group",
                showRowGroup: 'date',
                spanHeaderHeight: true,
                cellRenderer: 'agGroupCellRenderer',
                // cellRendererParams:{
                //     suppressCount: true,
                //     innerRenderer: GroupRowInnerRenderer,
                //     editable:false,
                //     checkbox: false,
                // },
                width: 50,
                colSpan: (params) => {
                    // console.log(params);
                    if(!params.data && params.node.field == "date"){
                        // console.log(params);
                        // console.log(params.node.parent.rowIndex);
                        return 2
                    }
                    return 1;
                },
                menuTabs: [],
                pinned: 'left',
                suppressMovable:true,
            },
            {
                headerName: "",
                field: "cost_center_name",
                hide: true,
                rowGroup: true,
            },
            {
                headerName: "核算单位",
                field: "cost_center_name_group",
                showRowGroup: 'cost_center_name',
                spanHeaderHeight: true,
                cellRenderer: 'agGroupCellRenderer',
                // cellRendererParams:{
                //     suppressCount: true,
                //     innerRenderer: GroupRowInnerRenderer,
                //     editable:false,
                //     checkbox: false,
                // },
                // colSpan: (params) => {
                //     // console.log(params);
                //     if(!params.data){
                //         console.log(params);
                //         // console.log(params.node.parent.rowIndex);
                //         // return 2
                //     }
                //     return 1;
                // },
                width: 100,
                menuTabs: [],
                pinned: 'left',
                suppressMovable:true,
            },
            {
                headerName: "客户组",
                field: "cus_group_name",
                width: 100,
                menuTabs: [],
                pinned: 'left',
                suppressMovable:true,
                spanHeaderHeight: true,
                aggFunc: 'cus_group_name',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
            },
        ];
        col = col.concat(this.setColumnDefs_total());
        col = col.concat(this.setColumnDefs_cost());
        console.log(col);
        return col;
    }
    setColumnDefs_total(){
        let _this = this;
        let col = [{
            headerName:'汇总',
            field:'total',
            menuTabs: [],
            children:[],
        }];
        col[0].children.push({
            headerName: '销售额',
            menuTabs: [],
            children:[{
                headerName:'',
                headerValueGetter:_this.headerValueGetter.bind(_this),
                // headerClass:'headerValueGetter',
                field: `totalSalesAmount`,
                menuTabs: [],
                width: 80,
                suppressMovable:true,
                pinned: 'left',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
                cellRenderer:saleCellRenderer,
                aggFunc: 'sum',
                valueFormatter:(params)=>{
                    let value;
                    if(params.value){
                        value = keepTwoDecimal(params.value);
                    }else{
                        value =  params.value;
                    }
                    if(!_this.state.tableConfig.showZero && value+'' == '0'){
                        return ''
                    }
                    return value
                },
            }]
        });
        col[0].children.push({
            headerName: '成本',
            menuTabs: [],
            children:[{
                headerName:'',
                headerValueGetter:_this.headerValueGetter.bind(_this),
                // headerClass:'headerValueGetter',
                field: `totalCostAmount`,
                menuTabs: [],
                width: 80,
                suppressMovable:true,
                pinned: 'left',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
                cellRenderer:saleCellRenderer,
                aggFunc: 'sum',
                valueFormatter:(params)=>{
                    let value;
                    if(params.value){
                        value = keepTwoDecimal(params.value);
                    }else{
                        value =  params.value;
                    }
                    if(!_this.state.tableConfig.showZero && value+'' == '0'){
                        return ''
                    }
                    return value
                },

            }]
        });
        col[0].children.push({
            headerName: '成本比例',
            menuTabs: [],
            children:[{
                headerName:'',
                headerValueGetter:_this.headerValueGetter.bind(_this),
                // headerClass:'headerValueGetter',
                field: `totalCostRatio`,
                menuTabs: [],
                width: 80,
                suppressMovable:true,
                pinned: 'left',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
                // aggFunc: 'sum',
                aggFunc: 'totalCostRatio',
                valueGetter: (params) => {
                    if(params.data.totalSalesAmount){
                        let value = params.data.totalCostAmount/params.data.totalSalesAmount;
                        return value;
                    }else{
                        return 0
                    }
                },
                valueFormatter:(params)=>{
                    let value;
                    if(params.value){
                        value = keepTwoDecimal(params.value*100)
                    }else{
                        value =  params.value;
                    }
                    if(!_this.state.tableConfig.showZero && value+'' == '0'){
                        return ''
                    }
                    return value+'%'
                },
            }]
        });
        col[0].children.push({
            headerName: '利润',
            menuTabs: [],
            children:[{
                headerName:'',
                headerValueGetter:_this.headerValueGetter.bind(_this),
                // headerClass:'headerValueGetter',
                field: `totalMarginAmount`,
                menuTabs: [],
                width: 80,
                suppressMovable:true,
                pinned: 'left',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
                aggFunc: 'sum',
                valueFormatter:(params)=>{
                    let value;
                    if(params.value){
                        value = keepTwoDecimal(params.value);
                    }else{
                        value =  params.value;
                    }
                    if(!_this.state.tableConfig.showZero && value+'' == '0'){
                        return ''
                    }
                    return value
                },
                // valueGetter: (params) => {
                //     if(params.data){
                //         let value = params.data.totalSalesAmount - params.data.totalCostAmount;
                //         return value;
                //     }else{
                //         return 0
                //     }
                // },

            }]
        });
        col[0].children.push({
            headerName: '利润率',
            menuTabs: [],
            children:[{
                headerName:'',
                headerValueGetter:_this.headerValueGetter.bind(_this),
                // headerClass:'headerValueGetter',
                field: `totalMarginRatio`,
                menuTabs: [],
                width: 80,
                suppressMovable:true,
                pinned: 'left',
                cellClassRules: {
                    // 'bg_gray': (params) => !params.data
                },
                aggFunc: 'totalMarginRatio',
                valueGetter: (params) => {
                    if(params.data.totalSalesAmount){
                        let value = params.data.totalMarginAmount/params.data.totalSalesAmount;
                        return value;
                    }else{
                        return 0
                    }
                },
                valueFormatter:(params)=>{
                    let value;
                    if(params.value){
                        value = keepTwoDecimal(params.value*100)
                    }else{
                        value =  params.value;
                    }
                    if(!_this.state.tableConfig.showZero && value+'' == '0'){
                        return ''
                    }
                    return value+'%'
                },
            }]
        });

        return col;
    }
    setColumnDefs_cost(){
        let _this = this;
        let { canteen_cost_report } = this.index;
        let { cost_type_dic, cost_category} = this.global;
        let col = [];
        // recordObj[key][`cost||${cost_category_id}||cost_amount`] = cost_amount;
        // recordObj[key][`cost||${cost_category_id}||cost_ratio`] = cost_ratio;
        // recordObj[key][`cost||${cost_category_id}||sales_amount`] = sales_amount;
        for(let cost_type in this.tableHead){
            let cost_type_col = {
                headerName: cost_type_dic[cost_type],
                field:cost_type,
                menuTabs: [],
                children:[]
            };
            for(let cost_category_id in this.tableHead[cost_type]){
                cost_type_col.children.push({
                    headerName: cost_category[cost_category_id].name,
                    menuTabs: [],
                    children:[{
                        headerValueGetter:_this.headerValueGetter.bind(_this),
                        // headerClass:'headerValueGetter',
                        field: `cost||${cost_category_id}||cost_amount`,
                        menuTabs: [],
                        width: 50,
                        // editable:true,
                        // valueFormatter:(params)=>{
                        //     return '￥' + params.value;
                        // },
                        // hide:!owl.isShowColId(`costPrice_${v.id}`),
                        suppressMovable:true,
                        cellClassRules: {
                            // 'bg_gray': (params) => !params.data
                        },
                        aggFunc: 'sum',
                        valueFormatter:(params)=>{
                            let value;
                            if(params.value){
                                value = keepTwoDecimal(params.value)
                            }else{
                                value = params.value;
                            }
                            if(!_this.state.tableConfig.showZero && value+'' == '0'){
                                return ''
                            }
                        },
                    }]
                });
                cost_type_col.children.push({
                    headerName: '%',
                    menuTabs: [],
                    children:[{
                        headerValueGetter:_this.headerValueGetter.bind(_this),
                        // headerClass:'headerValueGetter',
                        field: `cost||${cost_category_id}||cost_ratio`,
                        menuTabs: [],
                        width: 50,
                        // editable:true,
                        // valueFormatter:(params)=>{
                        //     return '￥' + params.value;
                        // },
                        // hide:!owl.isShowColId(`costPrice_${v.id}`),
                        suppressMovable:true,
                        cellClassRules: {
                            // 'bg_gray': (params) => !params.data
                        },
                        aggFunc: 'sum',
                        valueGetter: (params) => {
                            if(params.data.totalSalesAmount){
                                let value = params.data[`cost||${cost_category_id}||cost_amount`]/params.data.totalSalesAmount;
                                return value;
                            }else{
                                return 0
                            }
                        },
                        valueFormatter:(params)=>{
                            let value;
                            if(params.value){
                                value = keepTwoDecimal(params.value*100);
                            }else{
                                value = params.value;
                            }
                            if(!_this.state.tableConfig.showZero && value+'' == '0'){
                                return ''
                            }
                            return value +'%';
                        },
                    }]
                });
            }
            col.push(cost_type_col);
        }
        return col;
    }
    headerValueGetter(params){
        let ColId = params.column.colId;
        if(ColId == 'totalCostRatio'){
            let totalSalesAmount = this.calculateTotalByCol('totalSalesAmount');
            let totalCostAmount = this.calculateTotalByCol('totalCostAmount');
            if(!totalSalesAmount){
                return 0
            }
            return keepTwoDecimal(totalCostAmount/totalSalesAmount*100) +'%'
        }
        if(ColId == 'totalMarginRatio'){
            let totalSalesAmount = this.calculateTotalByCol('totalSalesAmount');
            let totalMarginAmount = this.calculateTotalByCol('totalMarginAmount');
            if(!totalSalesAmount){
                return 0
            }
            return keepTwoDecimal(totalMarginAmount/totalSalesAmount*100) +'%'
        }

        let value = this.calculateTotalByCol(ColId);
        // let value = 0;
        return value;
    };
    // 计算总数-列 headerValueGetter
    calculateTotalByCol(colId){
        let rowData = this.getRowData();
        if(rowData.length == 0){
            rowData = this.rowData;
        }
        let result = [];
        rowData.forEach(v=>{
            result.push(Number(v[colId]||0));
        });

        let sum = 0;
        try {
            sum = eval(result.join("+"))||0;
        }catch (e) {}
        sum = keepTwoDecimal(sum);
        return sum || 0;
    }
    SetAGOptions() {
        let _this = this;
        let cols = this.setColumnDefs();
        let rowData = this.rowData;
        console.log('-----SetAGOptions----');
        let grid_options = init_grid_options();
        this.gridOptions = Object.assign({}, grid_options, {
            groupDisplayType: 'custom',
            columnDefs:cols,
            rowData: rowData,
            components: {
                agColumnHeader: CustomHeader,
            },
            suppressMenuHide: true,
            defaultColDef: {
                editable: params => {
                    return false
                },
                resizable: true,//是否可以调整列大小，就是拖动改变列大小
                filter: true,  //开启刷选
                lockPinned: true,
            },
            rowDragManaged: true,
            suppressMoveWhenRowDragging: true,
            animateRows: true,
            groupHeaderHeight: 30,
            headerHeight:30,
            context: {
                owl_widget: _this
            },
            autoGroupColumnDef: {
                minWidth: 300,
            },
            groupDefaultExpanded:0,
            // groupRowRendererParams: {
            //     suppressCount: true,
            //     innerRenderer: GroupRowInnerRenderer,
            //     editable:false,
            //     checkbox: false,
            // },
            valueCache:1,
            onCellValueChanged: (e) => {
                // _this.onCellValueChanged(e);
            },
            onCellEditingStarted:(e)=>{
                _this.state.isEditing = true;
            },
            onCellEditingStopped:(e)=>{
                _this.state.isEditing = false;
            },
            getContextMenuItems: (e) => {
                // return _this.setAGMenus(e);
                return [];
            },
            getRowId: (params) => {
                return params.data.id;
            },
            onGridReady: function (params) {
                // let defaultSortModel = [
                //     { colId: 'cus_sales_no', sort: 'asc', sortIndex: 0 },
                //     { colId: 'timestamp', sort: 'asc', sortIndex: 0 },
                // ];
                // params.columnApi.applyColumnState({ state: defaultSortModel });
            },
            onFilterChanged:(params) => {
                // console.log('-------onFilterChanged----------');
                // _this.gridOptions.api.redrawRows();
            },
            // singleClickEdit: true,
            stopEditingWhenCellsLoseFocus:true,
            getRowStyle: params => {
                if (params && params.node && params.node.data && params.node.data.totalMarginAmount < 0) {
                    return { background: 'rgb(255 160 160)' };
                }
                if(!params.node.data){
                    if(params.node.aggData.totalMarginAmount < 0){
                        return { background: 'rgb(255 160 160)' };
                    }
                }
            },
            aggFuncs: {
                'cus_group_name': params => {
                    return '小计';
                },
                'totalCostRatio':params => {
                    let totalCostAmount = 0;
                    let totalSalesAmount = 0;
                    try{
                        params.rowNode.allLeafChildren.forEach(u=>{
                            totalCostAmount += u.data.totalCostAmount;
                            totalSalesAmount += u.data.totalSalesAmount;
                        })
                    }catch (e) {}
                    if(!totalSalesAmount){
                        return 0
                    }
                    let value = totalCostAmount/totalSalesAmount || 0
                    return value;
                },
                'totalMarginRatio':params => {
                    let totalMarginAmount = 0;
                    let totalSalesAmount = 0;
                    try{
                        params.rowNode.allLeafChildren.forEach(u=>{
                            totalMarginAmount += u.data.totalMarginAmount;
                            totalSalesAmount += u.data.totalSalesAmount;
                        })
                    }catch (e) {}
                    if(!totalSalesAmount){
                        return 0
                    }
                    let value = totalMarginAmount/totalSalesAmount || 0
                    return value;
                },

            },
        })
    }
    RenderAG() {
        // console.log('RenderAG');
        this.SetAGOptions();
        this.agGrid = new agGrid.Grid(this.myGrid_ref.el, this.gridOptions);

        onFullscreenChange((e)=>{return this.onFullscreenChange(e)})
    }
    getRowData(){
        let rowData = [];
        this.gridOptions.api.forEachNode(function (node) {
            if(node.data){
                rowData.push(node.data);
            }
        });
        // console.log(rowData);
        return rowData;
    }
}


Root.template = 'Canteen_cost_report_Root';


Root.props = {
    year_month: {type: String},
    LoadData: {type: Function, optional: true},
    toggleMenuMode: {type: Function, optional: true},
    CanteenLoadSaleData: {type: Function, optional: true},
    CanteenLoadCostData: {type: Function, optional: true},
}

// console.log(t_root);
// console.log(init_grid_options);


Root.components = {
    Toast,
    SalesModal,
    CostModal
}


export {
    Root
}
